package com.example.demo.Adapter;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.cardview.widget.CardView;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.example.demo.Activity.KlineChartActivity;
import com.example.demo.Activity.LoginActivity;
import com.example.demo.Activity.MainActivity;
import com.example.demo.Bean.Currency;
import com.example.demo.Bean.CurrencyState;
import com.example.demo.Bean.Userdata;
import com.example.demo.R;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.UpdateListener;

public class CurrencyAdapter extends RecyclerView.Adapter<CurrencyAdapter.ViewHolder>{

    private static final String TAG = "CurrencyAdapter";
    private Context mContext;
    private List<Currency> mCurrencyList;
    public String objectIdA = "uABmqqq0";
    public String objectIdB = "zXCk888I";
    public String objectIdC = "MWvT000B";
    public String objectIdD = "U8TDmmmx";
    public String objectIdE = "5Yr94448";

    public CurrencyAdapter(List<Currency> list, Context context) {
        mCurrencyList = list;
        mContext = context;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(mContext).inflate(R.layout.currency_item_layout, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        Currency currency = mCurrencyList.get(position);
        holder.currencyName.setText(currency.getId());
        Glide.with(mContext).load(currency.getImageId()).into(holder.currencyImage);
        SetTrend(currency.getId(), holder);
        /*暂无*/
        holder.cardView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(!(currency.getId().equals("A") || currency.getId().equals("B") || currency.getId().equals("C")
                        || currency.getId().equals("D") || currency.getId().equals("E"))){
                    Toast.makeText(mContext,"尚未发布，敬请期待！",Toast.LENGTH_SHORT).show();
                }
                else{
                    Intent intent=new Intent(mContext, KlineChartActivity.class);
                    intent.putExtra("currencyName",currency.getId());
                    mContext.startActivity(intent);
                }
            }
        });
    }

    @Override
    public int getItemCount() {
        return mCurrencyList.size();
    }

    static class ViewHolder extends RecyclerView.ViewHolder {
        CardView cardView;
        ImageView currencyImage;
        TextView currencyName;
        TextView currencyPrice;
        TextView currencyTrend;

        public ViewHolder(View view) {
            super(view);
            cardView = (CardView) view;
            currencyImage = (ImageView) view.findViewById(R.id.currency_image);
            currencyName = (TextView) view.findViewById(R.id.currency_name);
            currencyPrice = (TextView) view.findViewById(R.id.currency_price);
            currencyTrend = (TextView) view.findViewById(R.id.currency_trend);
        }
    }

    public void setCurrencylist(List<Currency> list) {
        mCurrencyList.clear();
        mCurrencyList = list;
        for(int i = 0; i < mCurrencyList.size(); i++) {
            Random rand = new Random();
            int index = rand.nextInt(7);
            int rid = mContext.getResources().getIdentifier("nav_icon" + String.valueOf(index),"drawable", mContext.getPackageName());
            mCurrencyList.get(i).setImageId(rid);
        }
        notifyDataSetChanged();
    }

    public static Thread[] findAllThreads() {   //返回所有线程列表
        ThreadGroup group = Thread.currentThread().getThreadGroup();
        ThreadGroup topGroup = group;
        /* 遍历线程组树，获取根线程组 */
        while ( group != null ){
            topGroup = group;
            group = group.getParent();
        }
        /* 激活的线程数加倍 */
        int estimatedSize = topGroup.activeCount() * 2;
        Thread[] slackList = new Thread[estimatedSize];
        /* 获取根线程组的所有线程 */
        int actualSize = topGroup.enumerate( slackList );
        /* copy into a list that is the exact size */
        Thread[] list = new Thread[actualSize];
        System.arraycopy( slackList, 0, list, 0, actualSize );
        return (list);
    }

    public void SetTrend(String currencyName, ViewHolder theHolder){
        if(currencyName.equals("A")){
            //先摧毁之前的同名FlushRatio线程，只留一个就好
            Thread[] list = findAllThreads();
            for(int i = 0; i < list.length; i++){
                if(list[i].getName().equals("FlushRatioA"))
                    list[i].interrupt();
            }
            new Thread(new Runnable() {
                @Override
                public void run() {
                    Thread.currentThread().setName("FlushRatioA");
                    BmobQuery<CurrencyState.A> mBmobQuery = new BmobQuery<>();
                    mBmobQuery.order("Date"); //按时间排序
                    while (!Thread.currentThread().isInterrupted()){
                        mBmobQuery.findObjects(new FindListener<CurrencyState.A>() {
                            @Override
                            public void done(List<CurrencyState.A> list, BmobException e) {
                                if (e == null) { //查询成功
                                    CurrencyState startState = list.get(0);
                                    CurrencyState endState = list.get(list.size() - 1);
                                    double ratio = (Float.parseFloat(endState.getClose()) - Float.parseFloat(startState.getOpen()))
                                            / Float.parseFloat(startState.getOpen());
                                    //更新LastRatio
                                    Currency currency = new Currency();
                                    currency.setLastRadio(String.format("%.2f", ratio * 100));
                                    currency.update(objectIdA, new UpdateListener() {
                                        @Override
                                        public void done(BmobException e) {
                                            if(e==null)
                                                Log.d("okex", "更新A涨幅成功：" + String.format("%.2f", Math.abs(ratio * 100)) + "%");
                                            else
                                                Log.d("okex", "更新A涨幅失败：");
                                        }
                                    });
                                    //更新显示的涨幅值
                                    String ratioSign = "";
                                    if(ratio < 0) {
                                        theHolder.currencyTrend.setTextColor(mContext.getResources().getColor(R.color.chart_green));
                                        ratioSign = "-";
                                    }
                                    else if(ratio > 0) {
                                        theHolder.currencyTrend.setTextColor(mContext.getResources().getColor(R.color.chart_red));
                                        ratioSign = "+";
                                    }
                                    else theHolder.currencyTrend.setTextColor(Color.BLACK);
                                    theHolder.currencyPrice.setText("$" + endState.getClose());
                                    theHolder.currencyTrend.setText(ratioSign + String.format("%.2f", Math.abs(ratio * 100)) + "%");
                                    Log.d("okex", "A：" + list.size() + "，" + String.format("%.2f", Math.abs(ratio * 100)) + "%");
                                }
                            }
                        });
                        try {
                            Thread.sleep(2000);
                        }catch (Exception e){
                            break;
                        }
                    }
                }
            }).start();
        }
        else if(currencyName.equals("B")){
            //先摧毁之前的同名FlushRatio线程，只留一个就好
            Thread[] list = findAllThreads();
            for(int i = 0; i < list.length; i++){
                if(list[i].getName().equals("FlushRatioB"))
                    list[i].interrupt();
            }
            new Thread(new Runnable() {
                @Override
                public void run() {
                    Thread.currentThread().setName("FlushRatioB");
                    BmobQuery<CurrencyState.B> mBmobQuery = new BmobQuery<>();
                    mBmobQuery.order("Date"); //按时间排序
                    while (!Thread.currentThread().isInterrupted()) {
                        mBmobQuery.findObjects(new FindListener<CurrencyState.B>() {
                            @Override
                            public void done(List<CurrencyState.B> list, BmobException e) {
                                if (e == null) { //查询成功
                                    CurrencyState startState = list.get(0);
                                    CurrencyState endState = list.get(list.size() - 1);
                                    double ratio = (Float.parseFloat(endState.getClose()) - Float.parseFloat(startState.getOpen()))
                                            / Float.parseFloat(startState.getOpen());
                                    //更新LastRatio
                                    Currency currency = new Currency();
                                    currency.setLastRadio(String.format("%.2f", ratio * 100));
                                    currency.update(objectIdB, new UpdateListener() {
                                        @Override
                                        public void done(BmobException e) {
                                            if(e==null)
                                                Log.d("okex", "更新B涨幅成功：" + String.format("%.2f", Math.abs(ratio * 100)) + "%");
                                            else
                                                Log.d("okex", "更新B涨幅失败：");
                                        }
                                    });
                                    //更新显示的涨幅值
                                    String ratioSign = "";
                                    if(ratio < 0) {
                                        theHolder.currencyTrend.setTextColor(mContext.getResources().getColor(R.color.chart_green));
                                        ratioSign = "-";
                                    }
                                    else if(ratio > 0) {
                                        theHolder.currencyTrend.setTextColor(mContext.getResources().getColor(R.color.chart_red));
                                        ratioSign = "+";
                                    }
                                    else theHolder.currencyTrend.setTextColor(Color.BLACK);
                                    theHolder.currencyPrice.setText("$" + endState.getClose());
                                    theHolder.currencyTrend.setText(ratioSign + String.format("%.2f", Math.abs(ratio * 100)) + "%");
                                    Log.d("okex", "B：" + list.size() + "，" + String.format("%.2f", Math.abs(ratio * 100)));
                                }
                            }
                        });
                        try {
                            Thread.sleep(2000);
                        }catch (Exception e){
                            break;
                        }
                    }
                }
            }).start();
        }
        else if(currencyName.equals("C")){
            //先摧毁之前的同名FlushRatio线程，只留一个就好
            Thread[] list = findAllThreads();
            for(int i = 0; i < list.length; i++){
                if(list[i].getName().equals("FlushRatioC"))
                    list[i].interrupt();
            }
            new Thread(new Runnable() {
                @Override
                public void run() {
                    Thread.currentThread().setName("FlushRatioC");
                    BmobQuery<CurrencyState.C> mBmobQuery = new BmobQuery<>();
                    mBmobQuery.order("Date"); //按时间排序
                    while (!Thread.currentThread().isInterrupted()) {
                        mBmobQuery.findObjects(new FindListener<CurrencyState.C>() {
                            @Override
                            public void done(List<CurrencyState.C> list, BmobException e) {
                                if (e == null) { //查询成功
                                    CurrencyState startState = list.get(0);
                                    CurrencyState endState = list.get(list.size() - 1);
                                    double ratio = (Float.parseFloat(endState.getClose()) - Float.parseFloat(startState.getOpen()))
                                            / Float.parseFloat(startState.getOpen());
                                    //更新LastRatio
                                    Currency currency = new Currency();
                                    currency.setLastRadio(String.format("%.2f", ratio * 100));
                                    currency.update(objectIdC, new UpdateListener() {
                                        @Override
                                        public void done(BmobException e) {
                                            if(e==null)
                                                Log.d("okex", "更新C涨幅成功：" + String.format("%.2f", Math.abs(ratio * 100)) + "%");
                                            else
                                                Log.d("okex", "更新C涨幅失败：");
                                        }
                                    });
                                    //更新显示的涨幅值
                                    String ratioSign = "";
                                    if(ratio < 0) {
                                        theHolder.currencyTrend.setTextColor(mContext.getResources().getColor(R.color.chart_green));
                                        ratioSign = "-";
                                    }
                                    else if(ratio > 0) {
                                        theHolder.currencyTrend.setTextColor(mContext.getResources().getColor(R.color.chart_red));
                                        ratioSign = "+";
                                    }
                                    else theHolder.currencyTrend.setTextColor(Color.BLACK);
                                    theHolder.currencyPrice.setText("$" + endState.getClose());
                                    theHolder.currencyTrend.setText(ratioSign + String.format("%.2f", Math.abs(ratio * 100)) + "%");
                                    Log.d("okex", "C：" + list.size() + "，" + String.format("%.2f", Math.abs(ratio * 100)));
                                }
                            }
                        });
                        try {
                            Thread.sleep(2000);
                        }catch (Exception e){
                            break;
                        }
                    }
                }
            }).start();
        }
        else if(currencyName.equals("D")){
            //先摧毁之前的同名FlushRatio线程，只留一个就好
            Thread[] list = findAllThreads();
            for(int i = 0; i < list.length; i++){
                if(list[i].getName().equals("FlushRatioD"))
                    list[i].interrupt();
            }
            new Thread(new Runnable() {
                @Override
                public void run() {
                    Thread.currentThread().setName("FlushRatioD");
                    BmobQuery<CurrencyState.D> mBmobQuery = new BmobQuery<>();
                    mBmobQuery.order("Date"); //按时间排序
                    while (!Thread.currentThread().isInterrupted()) {
                        mBmobQuery.findObjects(new FindListener<CurrencyState.D>() {
                            @Override
                            public void done(List<CurrencyState.D> list, BmobException e) {
                                if (e == null) { //查询成功
                                    CurrencyState startState = list.get(0);
                                    CurrencyState endState = list.get(list.size() - 1);
                                    double ratio = (Float.parseFloat(endState.getClose()) - Float.parseFloat(startState.getOpen()))
                                            / Float.parseFloat(startState.getOpen());
                                    //更新LastRatio
                                    Currency currency = new Currency();
                                    currency.setLastRadio(String.format("%.2f", ratio * 100));
                                    currency.update(objectIdD, new UpdateListener() {
                                        @Override
                                        public void done(BmobException e) {
                                            if(e==null)
                                                Log.d("okex", "更新D涨幅成功：" + String.format("%.2f", Math.abs(ratio * 100)) + "%");
                                            else
                                                Log.d("okex", "更新D涨幅失败：");
                                        }
                                    });
                                    //更新显示的涨幅值
                                    String ratioSign = "";
                                    if(ratio < 0) {
                                        theHolder.currencyTrend.setTextColor(mContext.getResources().getColor(R.color.chart_green));
                                        ratioSign = "-";
                                    }
                                    else if(ratio > 0) {
                                        theHolder.currencyTrend.setTextColor(mContext.getResources().getColor(R.color.chart_red));
                                        ratioSign = "+";
                                    }
                                    else theHolder.currencyTrend.setTextColor(Color.BLACK);
                                    theHolder.currencyPrice.setText("$" + endState.getClose());
                                    theHolder.currencyTrend.setText(ratioSign + String.format("%.2f", Math.abs(ratio * 100)) + "%");
                                    Log.d("okex", "D：" + list.size() + "，" + String.format("%.2f", Math.abs(ratio * 100)));
                                }
                            }
                        });
                        try {
                            Thread.sleep(2000);
                        }catch (Exception e){
                            break;
                        }
                    }
                }
            }).start();
        }
        else if(currencyName.equals("E")){
            //先摧毁之前的同名FlushRatio线程，只留一个就好
            Thread[] list = findAllThreads();
            for(int i = 0; i < list.length; i++){
                if(list[i].getName().equals("FlushRatioE"))
                    list[i].interrupt();
            }
            new Thread(new Runnable() {
                @Override
                public void run() {
                    Thread.currentThread().setName("FlushRatioE");
                    BmobQuery<CurrencyState.E> mBmobQuery = new BmobQuery<>();
                    mBmobQuery.order("Date"); //按时间排序
                    while (!Thread.currentThread().isInterrupted()) {
                        mBmobQuery.findObjects(new FindListener<CurrencyState.E>() {
                            @Override
                            public void done(List<CurrencyState.E> list, BmobException e) {
                                if (e == null) { //查询成功
                                    CurrencyState startState = list.get(0);
                                    CurrencyState endState = list.get(list.size() - 1);
                                    double ratio = (Float.parseFloat(endState.getClose()) - Float.parseFloat(startState.getOpen()))
                                            / Float.parseFloat(startState.getOpen());
                                    //更新LastRatio
                                    Currency currency = new Currency();
                                    currency.setLastRadio(String.format("%.2f", ratio * 100));
                                    currency.update(objectIdE, new UpdateListener() {
                                        @Override
                                        public void done(BmobException e) {
                                            if(e==null)
                                                Log.d("okex", "更新E涨幅成功：" + String.format("%.2f", Math.abs(ratio * 100)) + "%");
                                            else
                                                Log.d("okex", "更新E涨幅失败：");
                                        }
                                    });
                                    //更新显示的涨幅值
                                    String ratioSign = "";
                                    if(ratio < 0) {
                                        theHolder.currencyTrend.setTextColor(mContext.getResources().getColor(R.color.chart_green));
                                        ratioSign = "-";
                                    }
                                    else if(ratio > 0) {
                                        theHolder.currencyTrend.setTextColor(mContext.getResources().getColor(R.color.chart_red));
                                        ratioSign = "+";
                                    }
                                    else theHolder.currencyTrend.setTextColor(Color.BLACK);
                                    theHolder.currencyPrice.setText("$" + endState.getClose());
                                    theHolder.currencyTrend.setText(ratioSign + String.format("%.2f", Math.abs(ratio * 100)) + "%");
                                    Log.d("okex", "E：" + list.size() + "，" + String.format("%.2f", Math.abs(ratio * 100)));
                                }
                            }
                        });
                        try {
                            Thread.sleep(2000);
                        }catch (Exception e){
                            break;
                        }
                    }
                }
            }).start();
        }
    }
}
